package main

import (
	"context"
	"log"
	"net/http"
	"os"
	"os/signal"
	"rustdesk_api_server/global"
	"rustdesk_api_server/router"
	"syscall"
	"time"
)

func main() {
	log.Println("server starting...")
	route := router.NewRouter(":21114")

	err := global.Initialize()
	if err != nil {
		log.Fatalln("database initialize failed, error: ", err.Error())
		os.Exit(0)
	}

	go func() {
		if err := route.ListenAndServe(); err != nil && err != http.ErrServerClosed {
			log.Fatalln("listen and serve faile, error: ", err.Error())
		}
	}()

	log.Println("server started.")

	quit := make(chan os.Signal, 1)
	signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)
	<-quit
	log.Println("server stopping...")
	ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
	defer cancel()

	if err := route.Shutdown(ctx); err != nil {
		log.Fatalln("server shutdown failed, error: ", err.Error())
	}

	log.Println("server stopped.")
}
